<?php

namespace App\Tasks;

use App\Clients\Lakala\AccountAuthUserInfo;
use App\Clients\Lakala\MerTransQueryTranInfoSum;
use App\Clients\Lakala\MerTransSepQuerySeps;
use App\Clients\Yisheng\TermStlmTotal;
use App\Clients\Yisheng\TradeGetTotal;
use App\Models\MallDateFinance;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;

class MallGroupKtvSyncDatasTask extends MeiTuanMallTask
{
    public function handleQeqData($postData){
        $requestTime = date("YmdHis");
        $requestId = $requestTime.rand(1000000,9999999);
        $postData["requestId"] = $requestId;
        $postData["requestTime"] = $requestTime;
        $postData["reqTime"] = $requestTime;
        $postData["systemCode"] = "MERDASH";
        $postData["version"] = "1.0";
        return $postData;
    }

    /**
     * @throws GuzzleException
     */
    protected function changeIdentityAndMer($account,$merchantNo){
        $service = new AccountAuthUserInfo($account);
        $queryData = [
            "isGuest"=>true
        ];
        $service->loopExecute($queryData)->contents();


        $postData = ["isGuest"=>true];
        $postData = $this->handleQeqData($postData);
        $cookies = json_decode($account->cookies,true);
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "AUTHORIZATION"=>$cookies["authorization"],
        ];
        $cookieJar = new CookieJar();
        $client = new Client([
            "verify"=>false,
            "http_errors"=>false,
            'cookies' => $cookieJar,
        ]);
        $url = "https://m2.lakala.com/m/a/lams/merdash/queryAllMerList";
        $content = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
        $content = json_decode($content,true);
        $content = $content["data"];

        $roleData = [];
        foreach ($content as $cont){
            if($cont["merchantNo"] == $merchantNo){
                $roleData = $cont;
                break;
            }
        }
        $postData = [
            "method"=>"userIdentity.set",
            "lamsRoleId"=>$roleData["roleId"],
            "merDataSources"=>$roleData["merFrom"],
            "authUserId"=>"",
            "defaultMerInnerNo"=>$roleData["merInnerNo"],
            "defaultMerchantNo"=>$roleData["merchantNo"],
        ];
        $postData = $this->handleQeqData($postData);
        $url = "https://m2.lakala.com/m/a/mp3Ms/userIdentity/changeIdentityAndMer";
        $content = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
        $cookiesV = $cookieJar->toArray();
        $cookieStr = [];
        foreach ($cookiesV as $cookie){
            $cookieStr[] = $cookie["Name"]."=".$cookie["Value"];
        }
        $cookieStr = implode("; ",$cookieStr);
        $cookies["cookies"] = $cookieStr;
        return $cookies;

    }

    /**
     * @throws GuzzleException
     */
    protected function ysDatas($account, $queryDate): array
    {
        $incomeClient = new TradeGetTotal($account);
        $subClient = new TermStlmTotal($account);
        $response = $incomeClient->loopExecute($queryDate["income"])->contents();
        $income = round($response["totalAmount"] / 100,2);
        $response = $subClient->loopExecute($queryDate["sub"])->contents();
        $subaoumt = 0;
        if(!empty($response)){
            $subaoumt = round($response["receiveTotalAmount"] / 100,2);
        }
        return [
            "income"=>$income,
            "subaoumt"=>$subaoumt,
        ];
    }

    /**
     * @throws GuzzleException
     */
    protected function lakalaDatas($account, $cookies,$queryDate): array
    {
        $incomeClient = new MerTransQueryTranInfoSum($account);
        $incomeClient->setCookieJar($cookies);
        $subClient = new MerTransSepQuerySeps($account);
        $subClient->setCookieJar($cookies);
        $response = $incomeClient->loopExecute($queryDate["income"])->contents();
        $income = empty($response["settleAmt"]) ? 0 : $response["settleAmt"];
        $subaoumt = 0;
        $subQuery = $queryDate["sub"];
        $page = 1;
        $pageSize = 100;
        $subQuery["pageNum"] = $page;
        $subQuery["pageSize"] = $pageSize;
        $subQuery["page_no"] = $page;
        $subQuery["page_size"] = $pageSize;
        $response = $subClient->loopExecute($subQuery)->contents();
        $total = $response["total"];
        $pageItems = $response["pageItems"];
        foreach ($pageItems as $pageItem){
            $subaoumt += $pageItem["amt"];
        }
        $totalPage = ceil($total / $pageSize);
        if($totalPage >= 2){
            for($i=2;$i<=$totalPage;$i++){
                $subQuery["pageNum"] = $i;
                $subQuery["page_no"] = $i;
                $response = $subClient->loopExecute($subQuery)->contents();
                $total = $response["total"];
                $pageItems = $response["pageItems"];
                foreach ($pageItems as $pageItem){
                    $subaoumt += $pageItem["amt"];
                }
            }
        }
        $subaoumt = round($subaoumt,2);

        return [
            "income"=>$income,
            "subaoumt"=>$subaoumt,
        ];
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function execute(): void
    {
        $startDate = $this->maxDate(4);
        $diffDate = (strtotime(date("Y-m-d",time())) - strtotime(date("Y-m-d",strtotime($startDate)))) / 86400;
        $groupData = json_decode($this->mall->counts_datas,true);
        $accounts = [];
        $lakalaCookies = null;
        foreach ($groupData as $plat=>$data){
            $account = $this->account->account->accountSub->where("plamt",$plat)->first();
            $accounts[$plat] = $account;
            if($plat == "lakala"){
                $lakalaCookies = $this->changeIdentityAndMer($account,$data["merchant_no"]);
            }
        }
        $queryDates = [];
        foreach (range(0,$diffDate,1) as $index=>$item){
            $temp = [
                "udate"=>date("Y-m-d",strtotime($startDate) + 1 * $index * 86400)
            ];
            foreach ($groupData as $plat=>$data){
                switch ($plat){
                    case "ys":
                        $beginDate = date("Y-m-d H:i:s",strtotime($startDate) + 1 * $index * 86400);
                        $endDate = date("Y-m-d H:i:s",strtotime($beginDate) + 86399);
                        $temp[$plat]["income"] = [
                            "termCodes"=>$data["merchant_no"],
                            "tradeTime"=>[
                                $beginDate,
                                $endDate
                            ],
                            "tradeState"=>0,
                            "splitSettleFlag"=>100,
                            "searchField"=>"RefNo",
                        ];
                        $temp[$plat]["sub"] = [
                            "stlmDate"=>[
                                $beginDate,
                                $endDate
                            ],
                            "termCodes"=>$data["merchant_no"],
                        ];
                        break;
                    case "lakala":
                        $beginDate = date("Ymd",strtotime($startDate) + 1 * $index * 86400);
                        $sdate = date("Y-m-d",strtotime($startDate) + 1 * $index * 86400);
                        $temp[$plat]["s"] = $sdate;
                        $temp[$plat]["income"] = [
                            "endDate"=>$beginDate,
                            "endTime"=>"235959",
                            "merchantNos"=>$data["merchant_no"],
                            "merchantNo"=>$data["merchant_no"],
                            "openEntity"=>$data["merchant_no"],
                            "startDate"=>$beginDate,
                            "startTime"=>"000000",
                            "groupType"=>"tranDate",
                            "page"=>1,
                            "size"=>10,
                        ];
                        $temp[$plat]["sub"] = [
                            "end_date"=>$beginDate,
                            "merchant_no"=>$data["merchant_no"],
                            "openEntity"=>$data["merchant_no"],
                            "outOrgCode"=>"000000",
                            "recv_no"=>$data["poi_id"],
                            "start_date"=>$beginDate,
                        ];
                        break;
                    default:
                        throw new Exception("不存在该平台");
                }
            }
            $queryDates[] = $temp;
        }

        foreach ($queryDates as $queryDate){
            $udate = $queryDate["udate"];
            var_dump($udate);
            unset($queryDate["udate"]);
            $model = MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date",$udate)
                ->first();
            if(!empty($model) && $model->is_update == 1){
                continue;
            }
            $income = 0;
            $subaoumt = 0;
            foreach ($queryDate as $plat=>$data){
                $account = $accounts[$plat];
                switch ($plat){
                    case "ys":
                        $moneyDatas = $this->ysDatas($account,$data);
                        break;
                    case "lakala":
                        $moneyDatas = $this->lakalaDatas($account,$lakalaCookies,$data);
                        break;
                    default:
                        $moneyDatas = [
                            "income"=>0,
                            "subaoumt"=>0,
                        ];
                }
                $income += $moneyDatas["income"];
                $subaoumt += $moneyDatas["subaoumt"];
            }
            $income = round($income,2);
            $subaoumt = round($subaoumt,2);
            empty($model) and $model = new MallDateFinance;
            $model->bill_no = $udate;
            $model->merchant_no = $this->mall->merchant_no;
            $model->date = $udate;
            $model->income = $income;
            $model->settle_money = $subaoumt;
            $model->save();
        }


    }
}
